package com.iweb.day08;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author WuYongheng
 * @date 2021/11/14
 * @description 演示遍历时删除
 */
public class TestDelete {
    public static void main(String[] args) {
        List<String> nameList = new ArrayList<>();
        nameList.add("tom");
        nameList.add("jerry");
        nameList.add("kitty");
        nameList.add("kitty");
        nameList.add("tony");
        printList(nameList);
        remove3(nameList, "kitty");
        printList(nameList);
    }


    public static void printList(List<String> nameList) {
        for (String s : nameList) {
            System.out.print(s + " ");
        }
        System.out.println();
    }

    /**
     * 使用迭代器删除
     *
     * @param nameList
     * @param name     要删除的元素
     */
    public static void remove1(List<String> nameList, String name) {
        Iterator<String> iterator = nameList.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            if (name.equals(next)) {
                iterator.remove();
            }
        }
    }

    /**
     * 用for循环删除
     *
     * @param nameList
     * @param name 要删除的元素
     */

    public static void remove2(List<String> nameList, String name) {
        for (int i = 0; i < nameList.size(); i++) {
            if (name.equals(nameList.get(i))) {
                nameList.remove(i);
            }
        }
    }

    /**
     * 倒序删除，原理：未遍历的元素下标，不会受到影响
     * @param nameList
     * @param name
     */
    public static void remove3(List<String> nameList, String name) {
        for (int i = nameList.size() - 1; i >= 0; i--) {
            if (name.equals(nameList.get(i))) {
                nameList.remove(i);
            }
        }
    }
}